package hot100.h0911;

import java.util.HashMap;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 统计和为k的子数组的个数
 * @date 2024/9/11 20:04
 */
public class StatisiticSubArray {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        int k = 3;
        System.out.println(subarraySum(nums, k));
    }

    public static int subarraySum(int[] nums, int k) {
        // 使用哈希表来存储前缀和及其出现的次数
        HashMap<Integer, Integer> prefixSumCount = new HashMap<>();
        prefixSumCount.put(0, 1);
        int sum = 0;

        int count = 0;
        for (int num : nums) {
            sum += num;

            //是否存在前缀和
            if (prefixSumCount.containsKey(sum - k)) {
                count += prefixSumCount.get(sum - k);
            }
            prefixSumCount.put(sum, prefixSumCount.getOrDefault(sum, 0) + 1);
        }
        return count;
    }
}
